<template>
  <el-dialog :visible.sync="editFormVisible" width="750px" @close="dialogClose" :close-on-click-modal="false"
    :close-on-press-escape="false" top="10vh">
    <h2 slot="title" class="tx-c">{{ dialogTitle }}</h2>
    <el-form autocomplete="off" label-width="125px" :model="editForm" class="form_flex">
      <el-form-item v-for="(v, i) in editHeaderList" :key="i" :label="v.label" :class="v.required ? 'tip' : ''">
        <inputSearch :options="{type:'leader'}" v-if="v.prop === 'leader_id'" ref="e_Search" @onChange="nameChange"
          :middleList="middleList" />
        <inputSearch v-else-if="v.prop === 'departments_id'" ref="departmentSearch" type="departments"
          @onChange="departmentsChange" />
        <multipleSearch :options="{type:'all'}" v-else-if="v.prop === 'complete_id'" ref="e2_Search"
          @onChange="completionChange" :middleList="personList" :middleInfoList="middleInfoList" />
        <el-select size="medium" v-else-if="v.prop === 'leader_type'" v-model="editForm[v.prop]" clearable
          placeholder="请选择负责人类型">
          <el-option v-for="item in firstType" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select size="medium" v-else-if="v.prop === 'project_level'" v-model="editForm[v.prop]" clearable
          placeholder="请选择项目级别">
          <el-option v-for="item in projectLevel" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker v-else-if="v.prop === 'planned_completion_time' || v.prop === 'start_time'" size="medium"
          v-model="editForm[v.prop]" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期时间"
          :picker-options="pickerOptions[v.prop]" @change="changeDate()">
        </el-date-picker>
        <el-input v-else size="medium" :type="v.type" autosize clearable v-model="editForm[v.prop]"
          @mousewheel.native.prevent
            :placeholder="'请输入' + v.label">
          <template v-if="unitShow(v.prop)" slot="append">万元</template>
        </el-input>
      </el-form-item>
    </el-form>
    <el-form autocomplete="off" label-width="140px" class="form">
      <el-form-item v-for="(v,i) in upfilesObj" :key="'label' + v" :label="v">
        <div style="width: 500px">
          <p>
            <el-upload multiple action="/" :on-change="(file, fileList) => {onChangeFile(file, fileList, i)}"
              :on-remove="(file, fileList) => {onRemoveFile(file, fileList, i)}" :auto-upload="false"
              :file-list='fileObj[i]'>
              <el-button size="medium" type="primary">选择文件</el-button>
            </el-upload>
          </p>
          <div>
            <p v-for="(v) in uploadedList[i]" :key="'ed_' + v.id" class="p_cell flex-space-between"> <span
                class="overhide_ shou" @click="uploadFiles(v.file_path,v.file_name)"> <i class="el-icon-document"></i>
                {{v.file_name}}</span> <i @click="delFiles(v.id,i)" class="el-icon-close mr4 shou"></i> </p>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="flex-justify-bcenter">
      <el-button @click="editFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit" :loading="btnLoading">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {debounce,adminShow} from "@/utils/index";
  import {
    ApiprojectsAdd,
    ApiprojectsPut,
    ApiupLoadFiles,
    ApiprojectsUpload
  } from "@/api";
  import {isPhone} from "@/utils/test";
  import multipleSearch from "@/components/multipleSearch.vue"
  export default {
    components:{
      multipleSearch,
    },
    props: {
      info: {
        default: true,
        type: Boolean
      },
      dialogTitle: {
        default: "",
      },
      editHeaderList: {
        default: () => [],
      },
      editForm: {
        default: () => ({}),
      },
      firstType: {
        default: () => [],
      },
      projectLevel: {
        default: () => [],
      },
    },
    data() {
      return {
        adminShow: adminShow(),
        editFormVisible: false,
        btnLoading: false,
        middleList: [],
        personList: [],
        middleInfoList:[],
        pickerOptions: {
          start_time: {},
          planned_completion_time: {},
        },
        rules: ["name", "departments_id", "leader_id", "leader_type", "project_funds"],
        unitList: ["project_funds", "funds1"],
        activeName: '1',
        fileObj: {
          1: [],
          2: [],
          3: [],
          4: [],
        },
        uploadedList: {
          1: [],
          2: [],
          3: [],
          4: [],
        }, //已上传
        del: [],
        upfilesObj: {
          1: '项目申报书',
          2: '项目批准通知书',
          3: '项目计划书',
          4: '项目计划书批复件',
          // 5: '年度报告',
          // 6: '中期检查报告',
          // 7: '结题报告',
          // 8: '结题证明',
          // 9: '验收报告'
        }
      };
    },
    watch: {
      editFormVisible(flag) {
        if (flag) {
          this.$nextTick(() => {
            // if(this.info){
            this.$refs.departmentSearch[0].departments_id = this.editForm.departments_id;
            if (!this.adminShow && !this.editForm.id) {
              this.editForm.departments_id = this.$store.state.userInfo.department_id
              this.$refs.departmentSearch[0].departments_id = this.editForm.departments_id
            }

            //负责人回显
            if (this.editForm.leader_info) {
              this.middleList = [{
                employees_id: this.editForm.leader_id,
                employee: {
                  name: this.editForm.leader_info.name
                },
              }, ];
            }

            //完成人回显
            if (Array.isArray(this.editForm.complete_id) && this.editForm.complete_id.length > 0) {
              const arr = [],arr2 = [];
              for (const key in this.editForm.complete_name) {
                arr.push({
                  employees_id: Number(key),
                  employee:{
                    name:this.editForm.complete_name[key]
                  }
                })
                arr2.push(Number(key))
              }
              this.middleInfoList = arr
              this.personList = arr2
            }
            if (this.editForm.id) {
              for (const key in this.uploadedList) {
                this.uploadedList[key] = JSON.parse(JSON.stringify(this.editForm.files[key] ?? []))
              }
            }
            this.changeDate();
            // }
          });
        }
      },
    },
    methods: {
      unitShow(prop) {
        return this.unitList.includes(prop)
      },
      uploadFiles: debounce(function (url, name) {
        ApiupLoadFiles(url).then(res => {
          let a = document.createElement("a")
          a.href = URL.createObjectURL(res)
          a.download = name
          a.click()
          URL.revokeObjectURL(a.href)
        })
      }, 500, true),
      delFiles(id, i) {
        this.del.push(id)
        this.uploadedList[i] = this.uploadedList[i].filter(item => item.id !== id)
      },
      onChangeFile(file, fileList, i) {
        this.fileObj[i].push(file)
      },
      onRemoveFile(file, fileList, i) {
        this.fileObj[i] = fileList
      },
      dialogClose() {
        // if(this.info){
        this.$refs.departmentSearch[0].clear();
        this.$refs.e_Search[0].clear();
        this.$refs.e2_Search[0].clear();
        // }
        for (const key in this.fileObj) {
          this.fileObj[key] = []
          this.uploadedList[key] = []
        }
        this.del = []
      },
      departmentsChange(id) {
        this.editForm.departments_id = id;
      },
      nameChange(id) {
        this.editForm.leader_id = id;
      },
      completionChange(id) {
        this.editForm.complete_id = id;
      },
      uploadFiles: debounce(
        function (url, name) {
          ApiupLoadFiles(url).then((res) => {
            let a = document.createElement("a");
            a.href = URL.createObjectURL(res);
            a.download = name;
            a.click();
            URL.revokeObjectURL(a.href);
          });
        },
        500,
        true
      ),
      changeDate() {
        this.pickerOptions = {
          start_time: {
            disabledDate: (time) => {
              if (this.editForm.planned_completion_time) {
                return (
                  time.getTime() >= new Date(this.editForm.planned_completion_time).getTime()
                );
              }
              // else {
              //   return time.getTime() < Date.now() - 86400000;
              // }
            },
          },
          planned_completion_time: {
            disabledDate: (time) => {
              if (this.editForm.start_time) {
                // 开始日期
                return (
                  time.getTime() < new Date(this.editForm.start_time).getTime() - 86400000
                );
              }
              // else {
              //   return time.getTime() < Date.now() - 86400000;
              // }
            },
          },
        };
      },
      submit: debounce(
        function () {
          //提交  修改或新增
          this.submitInfo()
        },
        800,
        true
      ),
      submitInfo() {
        const options = {
          ...this.editForm
        };
        delete options.leader_info
        delete options.files
        for (const key of this.rules) {
          if (!options[key] && options[key] !== 0) {
            this.$message({
              type: "error",
              message: "必填信息请填写完整！",
            });
            return;
          }
        }
        if (options.contact_phone && !isPhone(options.contact_phone)) {
          this.$message.error("请输入正确联系人电话");
          return;
        }
        let count = 0
        for (const key in this.uploadedList) {
          count += (this.uploadedList[key].length + this.fileObj[key].length)
        }
        if (count === 0) {
          this.$message.error("至少上传一个文件");
          return;
        }
        this.btnLoading = true;
        options.project_funds = options.project_funds || 0;
        options.funds1 = options.funds1 || 0;

        const formData = new FormData()
        for (const key in options) {
          if (options[key] === null || options[key] === undefined) options[key] = ""
          //完成人
          if(key === 'complete_id'){  
            if(Array.isArray(options.complete_id) && options.complete_id.length > 0){
              options.complete_id.forEach(ele=>{
                formData.append('complete_id[]', ele)
              })
            }else{
              formData.append('complete_id[]', [])
            }
          }else{
            formData.append(key, options[key])
          }
        }
        const fileObj = this.fileObj
        for (const key in fileObj) {
          if (fileObj[key].length > 0) {
            fileObj[key].forEach(ele => {
              formData.append(`${key}[]`, ele.raw)
            });
          }
        }
        if (this.del.length > 0) {
          this.del.forEach(item => {
            formData.append(`del[]`, item)
          })
        } else {
          formData.append(`del[]`, [])
        }
        if (options.id) {
          //有ID就是修改
          ApiprojectsPut(formData, options.id, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            })
            .then((res) => {
              let message = '修改成功!'
              if (options.type === 'change') {
                message = '变更已提交管理员审核！'
              }
              this.$message({
                type: "success",
                message: message,
              });
              this.editFormVisible = false;
              this.$parent.getList();
            })
            .catch(() => {
              let message = '修改失败!'
              if (options.type === 'change') {
                message = '申请变更失败！'
              }
              this.$message({
                type: "error",
                message: message,
              });
            })
            .finally(() => {
              this.btnLoading = false;
            });
        } else {
          ApiprojectsAdd(formData, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            })
            .then((res) => {
              this.$message({
                type: "success",
                message: "添加成功!",
              });
              this.editFormVisible = false;
              this.$parent.getList();
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "添加失败!",
              });
            })
            .finally(() => {
              this.btnLoading = false;
            });
        }
      }
    },
  };
</script>

<style lang='less' scoped>
  .p_cell {
    padding-left: 4px;
    line-height: 1.8;

    span {
      margin-right: 40px;
    }
  }
</style>